package com.zhongshengnetwork.rightbe.login;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.os.Bundle;
//import android.support.v4.view.GestureDetectorCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.view.GestureDetectorCompat;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQToken;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.Constant.LetterConstant;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BroadcastDefine;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.DeviceUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.MD5;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.activity.MyWebActivity;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.dbmodel.LogindbModel;
import com.zhongshengnetwork.rightbe.dbservice.LogindbService;
import com.zhongshengnetwork.rightbe.dbservice.PeopledbService;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WXLoginModel;
import com.zhongshengnetwork.rightbe.gsonmodel.WXUserInfoModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;


import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 *
 */
public class LoginActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {
    private static final int Register_Request = 10000;
    private boolean flag=false;//标记edittext不会死循环
    private TopBarView topbar;
    private EditText accountText;
    private EditText passwordText;
    private TextView forgetPasswrodText;
    private Button loginButton;
    private Button registerButton;
    private ImageView wxIcon;
    private ImageView qqIcon;
    private ImageView wbIcon;
    private RelativeLayout loginthird;
    private RelativeLayout mView;
    private GestureDetectorCompat mDetector;
    private String password;
    //private CustomProgressDialog mDialog;
    private RelativeLayout thirdlogin;

    //以下是qq相关
    private static final String APP_ID = "1105905402";//官方获取的APPID
    private Tencent mTencent;
    private BaseUiListener mIUiListener;
    private UserInfo mUserInfo;

    private AVLoadingIndicatorView avi;

    private RelativeLayout bottom_layout;
    private ImageView agree_bg;
    private ImageView agree_img;
    private TextView a_title;
    private TextView p_title;
    private TextView c_title;
    private boolean isAgree = false;
    private Integer loginWay = 1; //登录方式1-只支持手机登录；3-微信和手机；7-微信、QQ和手机
    private boolean onlyMoblie = false;

    private void clickAgree(){
        if (isAgree == true){
            isAgree = false;
            agree_bg.setVisibility(View.VISIBLE);
            agree_img.setVisibility(View.INVISIBLE);
        }else {
            isAgree = true;
            agree_bg.setVisibility(View.INVISIBLE);
            agree_img.setVisibility(View.VISIBLE);
        }
    }

    private void shake(){
        ToastUtil.show(LoginActivity.this, "亲，请先阅读并勾选同意《用户协议》和《隐私政策》。");
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);//加载动画资源文件
        a_title.startAnimation(shake);
        p_title.startAnimation(shake);
        c_title.startAnimation(shake);
    }

    private void agreeView(){
        bottom_layout = (RelativeLayout) findViewById(R.id.bottom_layout);

        RelativeLayout click_layout = (RelativeLayout) findViewById(R.id.click_layout);
        click_layout.setClickable(true);
        click_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickAgree();
            }
        });

        agree_bg = (ImageView) findViewById(R.id.agree_bg);
        agree_bg.setClickable(true);
        agree_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickAgree();
            }
        });

        agree_img = (ImageView) findViewById(R.id.agree_img);
        agree_img.setClickable(true);
        agree_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickAgree();
            }
        });

        isAgree = getIntent().getBooleanExtra("isAgree",false);
        if (isAgree == true){
            agree_bg.setVisibility(View.INVISIBLE);
            agree_img.setVisibility(View.VISIBLE);
        }

        a_title = (TextView) findViewById(R.id.a_title);
        a_title.setClickable(true);
        a_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                clickAgree();
            }
        });

        p_title = (TextView) findViewById(R.id.p_title);
        p_title.setClickable(true);
        p_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent webIntent = new Intent(LoginActivity.this, MyWebActivity.class);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
                startActivity(webIntent);//用户协议
            }
        });

        c_title = (TextView) findViewById(R.id.c_title);
        c_title.setClickable(true);
        c_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent webIntent = new Intent(LoginActivity.this, MyWebActivity.class);
                webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuprivacy.do");
                startActivity(webIntent);//隐私政策
            }
        });

    }

    private void initApp(){
        PeopledbService.deleteAllData();
        LogindbService.deleteLoginModel();
        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.SXBlackAsyncKey, false);
        SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(LetterConstant.SXBlackPageKey, 0);
        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.SXStateKey, false);
        SPManageUtils.getInstance(CustomApplication.mContext).putSPInt(LetterConstant.SXTypeKey,LetterConstant.sx_all_open_type);
        SPManageUtils.getInstance(CustomApplication.mContext).putSPString(LetterConstant.InChatKey,"");
        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(LetterConstant.InMessageKey, false);

    }

    /**
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        onlyMoblie = getIntent().getBooleanExtra("onlyMoblie", false);
        agreeView();
        registerBoradcastReceiver();
        initApp();
        SPManageUtils.getInstance(CustomApplication.mContext).putSPBoolean(AdvertUtils.Smart_Rank_State, false);
        avi = (AVLoadingIndicatorView)findViewById(R.id.avi);
        mDetector = new GestureDetectorCompat(this, new MyGestureListener());
        mView = (RelativeLayout) findViewById(R.id.login_xml);
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        accountText = (EditText) findViewById(R.id.login_account);
        accountText.setText("");
        accountText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
               //System.out.print("beforeTextChanged:"+charSequence+"\n");
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //System.out.print("onTextChanged:"+charSequence+"\n");
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (flag) {
                    return;
                }
                //flag = true;
                /**
                 *
                 * 这部分是业务逻辑的代码块
                 */
                flag = false;
                //System.out.print("afterTextChanged\n");
            }
        });

        passwordText = (EditText) findViewById(R.id.login_password);
        passwordText.clearFocus();
        passwordText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        forgetPasswrodText = (TextView) findViewById(R.id.login_forget_password);
        forgetPasswrodText.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
        forgetPasswrodText.getPaint().setAntiAlias(true);//抗锯齿
        forgetPasswrodText.setClickable(true);
        forgetPasswrodText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                //System.out.print("forgetPasswrodText\n");
                hintKeyBoard();
                if (isAgree == false){
                    shake();
                    return;
                }
                startActivity(new Intent(LoginActivity.this, ForgetPasswrodActivity.class));
            }
        });

        loginButton = (Button) findViewById(R.id.login_button);
        registerButton = (Button) findViewById(R.id.register_button);

        loginthird = (RelativeLayout) findViewById(R.id.login_third);
        RelativeLayout thirdloginup = (RelativeLayout) findViewById(R.id.login_third_up);
        wxIcon = (ImageView) findViewById(R.id.login_third_wx);
        if (CustomApplication.mWxApi != null && CustomApplication.mWxApi.isWXAppInstalled() == false){
            wxIcon.setVisibility(View.GONE);
        }else {
            wxIcon = (ImageView) findViewById(R.id.login_third_wx);
            wxIcon.setClickable(true);
            wxIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //startActivity(new Intent(LoginActivity.this,BDThirdActivity.class));
                    hintKeyBoard();
                    if (isAgree == false){
                        shake();
                        return;
                    }
                    wxLogin();
                }
            });
        }


        //初始化qq主操作对象
        Tencent.setIsPermissionGranted(true);//必须调研这个再调用其他接口
        mTencent = Tencent.createInstance("1105905402", LoginActivity.this,"com.zhongshengnetwork.rightbe.fileprovider");
        qqIcon = (ImageView) findViewById(R.id.login_third_qq);
        qqIcon.setClickable(true);
        qqIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
//                 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
//                 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类
                hintKeyBoard();
                if (isAgree == false){
                    shake();
                    return;
                }
                avi.show();
                mIUiListener = new BaseUiListener();
                //all表示获取所有权限
                mTencent.login(LoginActivity.this,"all", mIUiListener);
            }
        });

        boolean isCancleGesture = getIntent().getBooleanExtra("isCancleGesture", false);
        if (isCancleGesture == true){
            bottom_layout.setVisibility(View.GONE);
            isAgree = true;
            topbar.getTitleView().setText("取消手势");
            registerButton.setVisibility(View.GONE);
            wxIcon.setVisibility(View.GONE);
            qqIcon.setVisibility(View.GONE);
            thirdloginup.setVisibility(View.GONE);
        }

        RelativeLayout login_xml = (RelativeLayout) findViewById(R.id.login_xml);
        login_xml.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
        TextView login_title = (TextView) findViewById(R.id.login_title);
        login_title.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        login_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        EditText login_account = (EditText) findViewById(R.id.login_account);
        login_account.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        login_account.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        login_account.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        TextView login_pstitle = (TextView) findViewById(R.id.login_pstitle);
        login_pstitle.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        login_pstitle.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        EditText login_password = (EditText) findViewById(R.id.login_password);
        login_password.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        login_password.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        login_password.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        Button login_button = (Button) findViewById(R.id.login_button);
        //login_button.setBackgroundResource(AppThemeUtils.getInstance().getComsytleBg());

        Button register_button = (Button) findViewById(R.id.register_button);
        //register_button.setBackgroundResource(AppThemeUtils.getInstance().getButtonBg());

        LinearLayout leftline = (LinearLayout) findViewById(R.id.leftline);
        leftline.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        LinearLayout rightline = (LinearLayout) findViewById(R.id.rightline);
        rightline.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());


        RelativeLayout loginicon = (RelativeLayout) findViewById(R.id.loginicon);
        RelativeLayout login_input = (RelativeLayout) findViewById(R.id.login_input);
        wxIcon.setVisibility(View.GONE);
        qqIcon.setVisibility(View.GONE);
        loginWay = 1;
        if (onlyMoblie == true || isCancleGesture == true){
            loginWay = 1;
        }else{
            if (CustomApplication.mWxApi != null && CustomApplication.mWxApi.isWXAppInstalled() == false){
                //没有微信登录
            }else{
                loginWay += 2;
            }
            if (mTencent != null && mTencent.isQQInstalled(CustomApplication.mContext) == false){
                //没有qq登录
            }else{
                loginWay += 4;
            }
        }
        if (loginWay == 1){
            topbar.setTitle("手机登录");
            login_input.setVisibility(View.VISIBLE);
            loginicon.setVisibility(View.GONE);
            loginthird.setVisibility(View.GONE);
        }else{
            thirdloginup.setVisibility(View.VISIBLE);
            loginicon.setVisibility(View.VISIBLE);
            login_input.setVisibility(View.GONE);
            if (loginWay == 3){//手机+微信
                login_button.setText("使用微信登录");
                register_button.setVisibility(View.GONE);
            }else if(loginWay == 5){//手机+qq
                register_button.setText("使用QQ登录");
                login_button.setVisibility(View.GONE);
            }else if(loginWay == 7){//手机+微信+qq
                login_button.setText("使用微信登录");
                register_button.setText("使用QQ登录");
            }
            wbIcon = (ImageView) findViewById(R.id.login_third_wb);
            wbIcon.setVisibility(View.VISIBLE);
            wbIcon.setClickable(true);
            wbIcon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                通过这句代码，SDK实现了QQ的登录，这个方法有三个参数，第一个参数是context上下文，第二个参数SCOPO 是一个String类型的字符串，表示一些权限
//                 官方文档中的说明：应用需要获得哪些API的权限，由“，”分隔。例如：SCOPE = “get_user_info,add_t”；所有权限用“all”
//                 第三个参数，是一个事件监听器，IUiListener接口的实例，这里用的是该接口的实现类
                    hintKeyBoard();
                    if (isAgree == false){
                        shake();
                        return;
                    }
                    finish();
                    Intent intent = new Intent(LoginActivity.this, LoginActivity.class);
                    intent.putExtra("isAgree", true);
                    intent.putExtra("onlyMoblie", true);
                    startActivity(intent);
                }
            });
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        if (mTencent != null) {
            //注销登录
            mTencent.logout(LoginActivity.this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.print("活动返回：onActivityResult\n");
        if (resultCode == RESULT_OK){
            if (requestCode == Register_Request){
                Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                //mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
                //发送广播
                sendBroadcast(mIntent);
                setResult(RESULT_OK);
                finish();
            }
        }
        if(requestCode == Constants.REQUEST_LOGIN){//qq登陆相关
            Tencent.onActivityResultData(requestCode,resultCode,data,mIUiListener);
        }
    }

    /**
         * 点击了返回导航按钮
         */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        hintKeyBoard();
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {
        Toast.makeText(LoginActivity.this, "你点击了右侧按钮", Toast.LENGTH_SHORT).show();
    }

    /**
     * 登录
     * @param v
     */
    public void onClickLogin(View v) {
        System.out.print("onClickLogin\n");
        hintKeyBoard();
        if (isAgree == false){
            shake();
            return;
        }
        if(loginWay == 1){
            //手机登录
        }else if(loginWay == 3 || loginWay == 7){
            //微信登录
            wxLogin();
            return;
        }
//        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//        boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
//        if(isOpen == true){
//            //隐藏键盘
//            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
//        }
        if (accountText.getText().length() < 11){
            Toast.makeText(LoginActivity.this, R.string.accont_error_tip, Toast.LENGTH_SHORT).show();
            return;
        }

        if (passwordText.getText().length() < 6){
            Toast.makeText(LoginActivity.this, R.string.password_error_tip, Toast.LENGTH_SHORT).show();
            return;
        }
        /*
        final CustomProgressDialog dialog = new CustomProgressDialog(this, "正在加载中",R.anim.frame);
        dialog.setmLoadingTip("正在登陆...");
        dialog.show();
        */
        avi.show();

        password = passwordText.getText().toString();
        password = MD5.GetMD5Code(password);
        System.out.print("password="+password+"\n");


        final Map<String, String> map = new HashMap<>();
        map.put(APIKey.accountKey, accountText.getText().toString());
        map.put(APIKey.passwordKey, password);

        //volley
        HttpsUtils.loginDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                System.out.print("~onSuccess~:"+data+"\n");
                try {
                    CommonModel commonModel = GsonTools.getCommonModel(data);
                    if(commonModel.getFlag().equals("1")){//登录成功
                        JSONObject jsonObject = CommonUtils.stringToJson(data);

                        LogindbModel model = GsonTools.getLoginModel(jsonObject.getString(APIKey.dataKey),password);
                        System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                        CustomApplication.loginModel.setRctoken(model.getRctoken());
                        CustomApplication.loginModel.setToken(model.getToken());
                        CustomApplication.loginModel.setExpires(model.getExpires());
                        CustomApplication.loginModel.setUid(model.getUid());
                        CustomApplication.loginModel.setHeader(model.getHeader());
                        CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                        CustomApplication.loginModel.setBackground(model.getBackground());
                        CustomApplication.loginModel.setNickname(model.getNickname());
                        CustomApplication.loginModel.setSex(model.getSex());
                        CustomApplication.loginModel.setSignature(model.getSignature());
                        CustomApplication.loginModel.setLocation(model.getLocation());
                        CustomApplication.loginModel.setUserauth(model.getUserauth());
                        CustomApplication.loginModel.setPayauth(model.getPayauth());
                        CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                        CustomApplication.loginModel.setMobile(model.getMobile());
                        CustomApplication.loginModel.setNeed(model.getNeed());
                        LogindbService.deleteLoginModel();
                        LogindbService.saveOrUpdateLogindbMode(model);

                        //System.out.print("~bg~:"+CustomApplication.loginModel.getBackground()+"\n");

                        Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                        //发送广播
                        sendBroadcast(mIntent);
                        setResult(RESULT_OK);
                        finish();
//                        if(onlyMoblie == true){
//                            final Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
//                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                            startActivity(intent);
//                        }

                    }else {//登录失败
                       Toast.makeText(CustomApplication.mContext,commonModel.getMsg(),Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                //dialog.dismiss();
                avi.hide();
            }

            @Override
            public void onError(String msg) {
                System.out.print("~onError~:"+msg+"\n");
                //dialog.dismiss();
                //avi.hide();
            }
        });

    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 注册
     * @param v
     */
    public void onClickRegister(View v) {
        System.out.print("onClickRegister\n");
        hintKeyBoard();
        if (isAgree == false){
            shake();
            return;
        }
        if (loginWay == 1){
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivityForResult(intent,Register_Request);
        }else if(loginWay == 5 || loginWay == 7){
            //qq登录
            avi.show();
            mIUiListener = new BaseUiListener();
            //all表示获取所有权限
            mTencent.login(LoginActivity.this,"all", mIUiListener);
        }

    }

    public void onClickXieYi(View v){
        hintKeyBoard();
        Intent webIntent = new Intent(LoginActivity.this, MyWebActivity.class);
        webIntent.putExtra(APIKey.urlKey, Constant.HOST+"api/system/weijuagreement.do");
        startActivity(webIntent);//用户协议
    }


    /**
     * 屏幕事件
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event){
        this.mDetector.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
        /**
         * 屏幕操作事件
         */
        private static final String DEBUG_TAG = "Gestures";
        @Override
        public boolean onDown(MotionEvent event) {
            Log.d(DEBUG_TAG,"onDown: " + event.toString());
            hintKeyBoard();
            /*
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            boolean isOpen=imm.isActive();//isOpen若返回true，则表示输入法打开
            if(isOpen == true){
                //隐藏键盘
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
            */
            return true;
        }

        @Override
        public boolean onFling(MotionEvent event1, MotionEvent event2,
                               float velocityX, float velocityY) {
            Log.d(DEBUG_TAG, "onFling: " + event1.toString()+event2.toString());
            return true;
        }
    }

    //发起微信登陆
    private void wxLogin(){
        /*
        mDialog = new CustomProgressDialog(this, "正在登陆...",R.anim.frame);
        mDialog.setmLoadingTip("正在登陆...");
        mDialog.show();
        */
        avi.show();
        final SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        CustomApplication.mWxApi.sendReq(req);
    }

    //这个方法会取得accesstoken  和openID
    private void getToken(String code){
        System.out.print("code="+code+"\n");
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+CustomApplication.WX_APPID+"&secret="+CustomApplication.WX_Secrect+"&code="+code+"&grant_type=authorization_code";
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                         @Override
                         public void onResponse(String s) {
                                 //Toast.makeText(LoginActivity.this, s, Toast.LENGTH_LONG).show();
                                 Log.i("aa", "get请求成功" + s);
                             final WXLoginModel wxLoginModel = GsonTools.getWXLoginModel(s);
                             if (wxLoginModel != null){
                                 //开始第三方登陆
                                 final Map<String,String> map = new HashMap<String, String>();
                                 map.put(APIKey.idKey,wxLoginModel.getUnionid());
                                 map.put(APIKey.typeKey, Constant.wxloginType+"");
                                 map.put("mobileid", DeviceUtils.getDeviceID());
                                 HttpsUtils.thirdloginDo(map, new HttpCallBack() {
                                     @Override
                                     public void onSuccess(String data) {
                                         CommonModel commonModel = GsonTools.getCommonModel(data);
                                         if (commonModel.getFlag().equals("1")){//登陆成功
                                            //mDialog.dismiss();
                                             avi.hide();
                                             LogindbModel model = GsonTools.getThirdLogindbModel(data);
                                             System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                                             CustomApplication.loginModel.setRctoken(model.getRctoken());
                                             CustomApplication.loginModel.setToken(model.getToken());
                                             CustomApplication.loginModel.setExpires(model.getExpires());
                                             CustomApplication.loginModel.setUid(model.getUid());
                                             CustomApplication.loginModel.setHeader(model.getHeader());
                                             CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                                             CustomApplication.loginModel.setBackground(model.getBackground());
                                             CustomApplication.loginModel.setNickname(model.getNickname());
                                             CustomApplication.loginModel.setSex(model.getSex());
                                             CustomApplication.loginModel.setSignature(model.getSignature());
                                             CustomApplication.loginModel.setLocation(model.getLocation());
                                             CustomApplication.loginModel.setUserauth(model.getUserauth());
                                             CustomApplication.loginModel.setPayauth(model.getPayauth());
                                             CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                                             CustomApplication.loginModel.setMobile(model.getMobile());
                                             CustomApplication.loginModel.setNeed(model.getNeed());
                                             LogindbService.deleteLoginModel();
                                             LogindbService.saveOrUpdateLogindbMode(model);

                                             //System.out.print("~bg~:"+CustomApplication.loginModel.getBackground()+"\n");
                                             Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                                             //发送广播
                                             sendBroadcast(mIntent);
                                             setResult(RESULT_OK);
                                             finish();
                                         }else {
                                            if (commonModel.getCode().equals("10044")){//还没有绑定账号
                                                //获取微信信息
                                                getWXInfo(wxLoginModel);
                                            }else {
                                                //mDialog.dismiss();
                                                avi.hide();
                                                CustomApplication.showTip(commonModel,LoginActivity.this);
                                            }
                                         }
                                     }

                                     @Override
                                     public void onError(String msg) {
                                         //mDialog.dismiss();
                                         avi.hide();
                                     }
                                 });
                             }else {
                                 //mDialog.dismiss();
                                 avi.hide();
                             }

                             }
                     }, new Response.ErrorListener() {
                         @Override
                         public void onErrorResponse(VolleyError volleyError) {
                            // mDialog.dismiss();
                             avi.hide();
                                 //Toast.makeText(LoginActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                                 Log.i("aa", "get请求失败" + volleyError.toString());
                             }
                     });
                 //设置取消取消http请求标签 Activity的生命周期中的onStiop()中调用
                 request.setTag("volleyget");
                 CustomApplication.requestQueue.add(request);
    }

    //获取微信信息
    private void getWXInfo(final WXLoginModel wxLoginModel){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="
                + wxLoginModel.getAccess_token()
                + "&openid="
                + wxLoginModel.getOpenid();
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                //Toast.makeText(LoginActivity.this, s, Toast.LENGTH_LONG).show();
                Log.i("aa", "get请求成功" + s);
                //mDialog.dismiss();
                avi.hide();
                // 编码后的json
                try {
                    String json = new String(s.getBytes("ISO-8859-1"), "UTF-8");
                    Log.i("utf8", "get请求成功" + json);
                    WXUserInfoModel wxUserInfoModel = GsonTools.getWXUserInfoModel(json);
                    Intent intent = new Intent(LoginActivity.this,BDThirdActivity.class);
                    intent.putExtra(APIKey.idKey,wxLoginModel.getUnionid());
                    intent.putExtra(APIKey.typeKey,Constant.wxloginType);
                    intent.putExtra(APIKey.nicknameKey,wxUserInfoModel.getNickname());
                    intent.putExtra(APIKey.headerKey,wxUserInfoModel.getHeadimgurl());
                    startActivityForResult(intent,Register_Request);
                }catch (Exception e){

                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //mDialog.dismiss();
                avi.hide();
                //Toast.makeText(LoginActivity.this, volleyError.toString(), Toast.LENGTH_LONG).show();
                Log.i("aa", "get请求失败" + volleyError.toString());
            }
        });
        //设置取消取消http请求标签 Activity的生命周期中的onStiop()中调用
        request.setTag("volleyget");
        CustomApplication.requestQueue.add(request);
    }

    /**
     * 广播接收者
     * @author Gordon
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(BroadcastDefine.WX_Login)) {
                int result = intent.getIntExtra("errCode",-1);
                if (result == 0){
                    //getToken(intent.getStringExtra(APIKey.codeKey));
                    wxLoginDo(intent.getStringExtra(APIKey.codeKey));
                }else{
                    //mDialog.dismiss();
                    avi.hide();
                    Toast.makeText(LoginActivity.this,"登陆失败",Toast.LENGTH_SHORT).show();
                }
            }
        }
    };

    /**
     * 注册广播
     * @author Gordon
     */
    public void registerBoradcastReceiver(){
        IntentFilter myIntentFilter = new IntentFilter();
        //添加接收广播类型
        myIntentFilter.addAction(BroadcastDefine.WX_Login);
        //注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    //以下是qq相关
    /**
     * 自定义监听器实现IUiListener接口后，需要实现的3个方法
     * onComplete完成 onError错误 onCancel取消
     */
    private class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object response) {
            Log.e("TAG", "response:" + response);
            JSONObject obj = (JSONObject) response;
            try {
                final String openID = obj.getString("openid");
                String accessToken = obj.getString("access_token");
                String expires = obj.getString("expires_in");
                mTencent.setOpenId(openID);
                mTencent.setAccessToken(accessToken,expires);
                QQToken qqToken = mTencent.getQQToken();
                mUserInfo = new UserInfo(getApplicationContext(),qqToken);
                mUserInfo.getUserInfo(new IUiListener() {
                    @Override
                    public void onComplete(Object response) {
                        Log.e("TAG","登录成功"+response.toString());
                        final JSONObject jo = (JSONObject) response;
                        try{
                            String nickName = jo.getString("nickname");
                            final Map<String,String> map = new HashMap<String, String>();
                            map.put(APIKey.idKey,openID);
                            map.put("nickname",nickName);
                            HttpsUtils.qqloginDo(map, new HttpCallBack() {
                                @Override
                                public void onSuccess(String data) {
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")) {//登陆成功
                                        LogindbModel model = GsonTools.getThirdLogindbModel(data);
                                        System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                                        CustomApplication.loginModel.setRctoken(model.getRctoken());
                                        CustomApplication.loginModel.setToken(model.getToken());
                                        CustomApplication.loginModel.setExpires(model.getExpires());
                                        CustomApplication.loginModel.setUid(model.getUid());
                                        CustomApplication.loginModel.setHeader(model.getHeader());
                                        CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                                        CustomApplication.loginModel.setBackground(model.getBackground());
                                        CustomApplication.loginModel.setNickname(model.getNickname());
                                        CustomApplication.loginModel.setSex(model.getSex());
                                        CustomApplication.loginModel.setSignature(model.getSignature());
                                        CustomApplication.loginModel.setLocation(model.getLocation());
                                        CustomApplication.loginModel.setUserauth(model.getUserauth());
                                        CustomApplication.loginModel.setPayauth(model.getPayauth());
                                        CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                                        CustomApplication.loginModel.setMobile(model.getMobile());
                                        CustomApplication.loginModel.setNeed(model.getNeed());
                                        LogindbService.deleteLoginModel();
                                        LogindbService.saveOrUpdateLogindbMode(model);
                                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();

                                        //System.out.print("~bg~:"+CustomApplication.loginModel.getBackground()+"\n");
                                        Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                                        //发送广播
                                        sendBroadcast(mIntent);
                                        setResult(RESULT_OK);
                                        finish();
                                    }else {
                                        avi.hide();
                                        ToastUtil.show(LoginActivity.this, commonModel.getMsg());
                                    }
                                }

                                @Override
                                public void onError(String msg) {
                                    avi.hide();
                                    ToastUtil.show(LoginActivity.this, msg);
                                }
                            });
                        }catch (Exception e){
                            avi.hide();
                            ToastUtil.show(LoginActivity.this, "登录失败");
                        }

                        /*
                        //开始第三方登陆
                        final Map<String,String> map = new HashMap<String, String>();
                        map.put(APIKey.idKey,openID);
                        map.put(APIKey.typeKey, Constant.qqloginType+"");
                        map.put("mobileid", DeviceUtils.getDeviceID());
                        HttpsUtils.thirdloginDo(map, new HttpCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                CommonModel commonModel = GsonTools.getCommonModel(data);
                                if (commonModel.getFlag().equals("1")){//登陆成功
                                    //mDialog.dismiss();
                                    avi.hide();
                                    LogindbModel model = GsonTools.getThirdLogindbModel(data);
                                    System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                                    CustomApplication.loginModel.setRctoken(model.getRctoken());
                                    CustomApplication.loginModel.setToken(model.getToken());
                                    CustomApplication.loginModel.setExpires(model.getExpires());
                                    CustomApplication.loginModel.setUid(model.getUid());
                                    CustomApplication.loginModel.setHeader(model.getHeader());
                                    CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                                    CustomApplication.loginModel.setBackground(model.getBackground());
                                    CustomApplication.loginModel.setNickname(model.getNickname());
                                    CustomApplication.loginModel.setSex(model.getSex());
                                    CustomApplication.loginModel.setSignature(model.getSignature());
                                    CustomApplication.loginModel.setLocation(model.getLocation());
                                    CustomApplication.loginModel.setUserauth(model.getUserauth());
                                    CustomApplication.loginModel.setPayauth(model.getPayauth());
                                    LogindbService.deleteLoginModel();
                                    LogindbService.saveOrUpdateLogindbMode(model);

                                    //System.out.print("~bg~:"+CustomApplication.loginModel.getBackground()+"\n");
                                    Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                                    //发送广播
                                    sendBroadcast(mIntent);
                                    setResult(RESULT_OK);
                                    finish();
                                }else {
                                    if (commonModel.getCode().equals("10044")){//还没有绑定账号
                                        try {
                                            int ret = jo.getInt("ret");
                                            System.out.println("json=" + String.valueOf(jo));
                                            String nickName = jo.getString("nickname");
                                            String gender = jo.getString("gender");
                                            Intent intent = new Intent(LoginActivity.this,BDThirdActivity.class);
                                            intent.putExtra(APIKey.idKey,openID);
                                            intent.putExtra(APIKey.typeKey,Constant.qqloginType);
                                            intent.putExtra(APIKey.nicknameKey,nickName);
                                            intent.putExtra(APIKey.headerKey,"");
                                            startActivityForResult(intent,Register_Request);
                                        }catch (Exception e){

                                        }
                                    }else {
                                        //mDialog.dismiss();
                                        avi.hide();
                                        CustomApplication.showTip(commonModel,LoginActivity.this);
                                    }
                                }
                            }

                            @Override
                            public void onError(String msg) {
                                //mDialog.dismiss();
                                avi.hide();
                            }
                        });
                        */
                    }

                    @Override
                    public void onError(UiError uiError) {
                        Log.e("TAG","登录失败"+uiError.toString());
                        avi.hide();
                    }

                    @Override
                    public void onCancel() {
                        Log.e("TAG","登录取消");
                        avi.hide();
                    }

                    @Override
                    public void onWarning(int i) {

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError uiError) {
            Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
            avi.hide();
        }

        @Override
        public void onCancel() {
            Toast.makeText(LoginActivity.this, "授权取消", Toast.LENGTH_SHORT).show();
            avi.hide();
        }

        @Override
        public void onWarning(int i) {

        }

    }

    //微信登录
    private void wxLoginDo(String code){
        final Map<String,String> map = new HashMap<String, String>();
        map.put(APIKey.codeKey,code);
        map.put("mobileid", DeviceUtils.getDeviceID());
        map.put("flag","1");
        HttpsUtils.wxloginDo(map, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                CommonModel commonModel = GsonTools.getCommonModel(data);
                if (commonModel.getFlag().equals("1")){//登陆成功
                    //mDialog.dismiss();
                    avi.hide();
                    LogindbModel model = GsonTools.getThirdLogindbModel(data);
                    System.out.print("~rctoken~:"+model.getRctoken()+"\n");
                    CustomApplication.loginModel.setRctoken(model.getRctoken());
                    CustomApplication.loginModel.setToken(model.getToken());
                    CustomApplication.loginModel.setExpires(model.getExpires());
                    CustomApplication.loginModel.setUid(model.getUid());
                    CustomApplication.loginModel.setHeader(model.getHeader());
                    CustomApplication.loginModel.setThumbheader(model.getThumbheader());
                    CustomApplication.loginModel.setBackground(model.getBackground());
                    CustomApplication.loginModel.setNickname(model.getNickname());
                    CustomApplication.loginModel.setSex(model.getSex());
                    CustomApplication.loginModel.setSignature(model.getSignature());
                    CustomApplication.loginModel.setLocation(model.getLocation());
                    CustomApplication.loginModel.setUserauth(model.getUserauth());
                    CustomApplication.loginModel.setPayauth(model.getPayauth());
                    CustomApplication.loginModel.setWeiJuId(model.getWeiJuId());
                    CustomApplication.loginModel.setMobile(model.getMobile());
                    CustomApplication.loginModel.setNeed(model.getNeed());
                    LogindbService.deleteLoginModel();
                    LogindbService.saveOrUpdateLogindbMode(model);

                    //System.out.print("~bg~:"+CustomApplication.loginModel.getBackground()+"\n");
                    Intent mIntent = new Intent(BroadcastDefine.Login_Success_Action);
                    //发送广播
                    sendBroadcast(mIntent);
                    setResult(RESULT_OK);
                    finish();
                }else {
                    if (commonModel.getCode().equals("10044")){//还没有绑定账号
                        //获取微信信息
                        //getWXInfo(wxLoginModel);
                    }else {
                        //mDialog.dismiss();
                        avi.hide();
                        CustomApplication.showTip(commonModel,LoginActivity.this);
                    }
                }
            }

            @Override
            public void onError(String msg) {
                //mDialog.dismiss();
                avi.hide();
            }
        });
    }

}
